#!/bin/env python

import time
import cv2
import numpy as np

pic_path = "../resource/pic/img_005.jpg"
windowName = "adaptiveThreshold"

cv2.namedWindow(windowName, cv2.WINDOW_NORMAL)
cv2.resizeWindow(windowName, 500 * 1, 500)

cv2.namedWindow("raw", cv2.WINDOW_NORMAL)
cv2.resizeWindow("raw", 500 * 1, 500)

pic1_gray = cv2.imread(pic_path, cv2.IMREAD_GRAYSCALE)
cv2.imshow("raw", pic1_gray)

def trackbarCallback(value):
    print(value)

new_blocksize = 3
new_max_value = 255

old_blocksize = new_blocksize
old_max_value = new_max_value

cv2.createTrackbar('blocksize', windowName, old_blocksize, 50, trackbarCallback)
cv2.createTrackbar('max', windowName, old_max_value, 255, trackbarCallback)

# 自适应二值化
img = cv2.adaptiveThreshold(pic1_gray, old_max_value, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, old_blocksize, cv2.THRESH_BINARY)

cv2.imshow(windowName, img)

while True:
    if cv2.waitKey(1) == ord('q'):
        break

    new_blocksize = cv2.getTrackbarPos('blocksize', windowName)
    new_max_value = cv2.getTrackbarPos('max', windowName)

    if new_blocksize != old_blocksize and new_blocksize % 2 == 1 and new_blocksize > 1:
        print("blocksize:", new_blocksize)
        old_blocksize = new_blocksize
        img = cv2.adaptiveThreshold(pic1_gray, old_max_value, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, old_blocksize, 0)
        cv2.imshow(windowName, img)

    if new_max_value != old_max_value:
        print("max_value:", new_max_value)
        old_max_value = new_max_value
        img = cv2.adaptiveThreshold(pic1_gray, old_max_value, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, old_blocksize, 0)
        cv2.imshow(windowName, img)

print('销毁窗口')
cv2.destroyAllWindows()


